import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/views/Layout.vue'
import HomePage from '@/views/home/index.vue'
import TopCategory from '@/views/category/index.vue'
import SubCategory from '@/views/category/SubCategory.vue'
import GoodsPage from '@/views/goods/index.vue'
import LoginPage from '@/views/login/index.vue'
import CartPage from '@/views/cart/index.vue'
import CheckoutPage from "@/views/member/pay/checkout.vue";
import {useUserStore} from "@/store/modules/user";
import PayPage from '@/views/member/pay/index.vue';
import MemberLayout from '@/views/member/Layout.vue'
import MemberHome from '@/views/member/home/index.vue'
import {storeToRefs} from "pinia";


const routes = [
    {
      path: '/',
      component: Layout,
      children: [
        {
          path: '/',
          component: HomePage
        },
        {
          path:'category/:id',
          component:TopCategory,
        },
        {
          path:'category/sub/:id',
          component:SubCategory
        },
        {
          path:'/product/:id',
          component:GoodsPage
        },
        {
          path:'/cart',
          component: CartPage
        },
        {
          path:'/member/checkout',
          component:CheckoutPage
        },
        {
          path:'member/pay',
          component: PayPage
        },
        {
          path:'/member',
          component: MemberLayout,
          children:[
            {
              path:'/member',
              component:MemberHome
            }
          ]
        }
      ],
    },
    {
      path:'/login',
      component:LoginPage
    }
  ]

const scrollBehavior = function scrollBehavior(to, from, savedPosition) {
  if (savedPosition) {
    // 若路由前的页面有保存，则跳转至保存位
    return savedPosition
  }
  else {
    // 跳转回顶部
    return {
      x: 0,
      y: 0
    }
  }
  
}

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior,
})
// 路由切换前的路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const {profile:{token}} = storeToRefs(userStore)
  //   跳转去member开头的地址却没登陆
  if(to.path.startsWith('member') && !token) {
    next({path:'/login', query:{redirectUrl:to.fullPath}})
  }
  next()
})

export default router
